package socket;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class Server {
    private List<PrintWriter> allout = Collections.synchronizedList(new ArrayList<>());

    private ServerSocket serverSocket;
    public Server() {
            try {
                System.out.println("服务端启动中.....");
                serverSocket = new ServerSocket(8088);
                System.out.println("服务端已启动!");
            } catch (IOException e) {
                e.printStackTrace();
            }
    }
    public void start(){
        while (true) {
            try {
                System.out.println("等待客户端连接");
                Socket socket = serverSocket.accept();
                System.out.println("客户端以连接");
                ClientHandler2 c2 = new ClientHandler2(socket);
                Thread t1 = new Thread(c2);
                t1.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) {
        new Server().start();
    }
    private class ClientHandler2 implements Runnable{
        private Socket socket;
        private String host;
        public ClientHandler2(Socket socket1){socket=socket1;
        host = socket1.getInetAddress().getHostAddress();
        }
        private void sendMessage(String line ){
            System.out.println(line);
            synchronized (allout) {
                allout.forEach(p->p.println(line));
//                for (PrintWriter p : allout) {
//                    p.println(line);
//                }
            }
        }
        public void run() {
            PrintWriter pw = null;
            try {
                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);
                String s;
                OutputStream os = socket.getOutputStream();
                OutputStreamWriter isw = new OutputStreamWriter(os,StandardCharsets.UTF_8);
                BufferedWriter bw = new BufferedWriter(isw);
                pw = new PrintWriter(bw,true);
                synchronized (allout) { allout.add(pw); }
                sendMessage(host+"上线了，当前在线人数"+allout.size());
                while ((s=br.readLine())!=null) {
                    sendMessage(host+"说"+s);
                }
            } catch (IOException e) {
            }finally {
                synchronized (allout) { allout.remove(pw); }
                sendMessage(host+"下线了，当前在线人数"+allout.size());
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

